package com.wang.springbootinit.service.impl.GenChart;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wang.springbootinit.Listener.ExcelNoModelDataListener;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.constant.BISystemEnum;
import com.wang.springbootinit.constant.CommonConstant;
import com.wang.springbootinit.constant.FileEnum;
import com.wang.springbootinit.constant.UserConstant;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.exception.ThrowUtils;
import com.wang.springbootinit.mapper.SourceFileMapper;
import com.wang.springbootinit.minio.MinioUtil;
import com.wang.springbootinit.model.dto.chart.GenChartByAiRequest;
import com.wang.springbootinit.model.entity.*;
import com.wang.springbootinit.model.enums.ChartStatusEnum;
import com.wang.springbootinit.model.result.BIResponseResult;
import com.wang.springbootinit.model.vo.BIResponse;
import com.wang.springbootinit.service.ChartService;
import com.wang.springbootinit.service.IntegralService;
import com.wang.springbootinit.service.SparkInfoService;
import com.wang.springbootinit.service.UserService;
import com.wang.springbootinit.sparkAi.AiAnalyseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 图表生成后置处理器
 */

@Slf4j
@Service("GenChartAfterHandler")
public class GenChartAfterHandler {
    @Resource
    private ChartService chartService;
    @Resource
    private SparkInfoService sparkInfoService;
    @Resource
    private UserService userService;
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private SourceFileMapper sourceFileMapper;
    /**
     * 同步后置处理器
     */
    public BIResponseResult syncGenChartHandler(User loginUser, GenChartByAiRequest param, AiAnalyseModel analyseModel, String excelInfo){
        try {
            String answer = analyseModel.getContent();
            String[] split = answer.split("【【【【【");
            if (split.length < 3) {
                new BusinessException(BISystemEnum.ANALYSE_ERROR.getCode(), "AI 生成错误");
            }

            String chartCode = split[1].trim(); //生成的echarts图表代码 option
            String chartResult = split[2].trim(); //生成的数据结论

            //将生成的数据插入到数据库中
            Chart chart = new Chart();
            chart.setName(param.getName());
            chart.setGoal(param.getGoal());
            chart.setChartType(param.getChartType());
            chart.setChartData(excelInfo);
            chart.setGenchart(chartCode);
            chart.setGetResult(chartResult);
            chart.setUserId(loginUser.getId());
            chart.setStatus(ChartStatusEnum.SUCCEED.getValue());
            chart.setExecMessage(answer);
            chartService.save(chart);

            /**
             * 分析记录
             */
            SparkInfo sparkInfo = new SparkInfo();
            sparkInfo.setChartId(chart.getId());
            sparkInfo.setUserId(loginUser.getId());
            sparkInfo.setCompletionTokens(analyseModel.getCompletionTokens());
            sparkInfo.setPromptTokens(analyseModel.getPromptTokens());
            sparkInfo.setTotalTokens(analyseModel.getTotalTokens());
            sparkInfo.setIsSuccess(this.getIsSuccess(analyseModel.getIsSuccess()));
            sparkInfoService.save(sparkInfo);

            /**
             * 扣除调用次数
             */
            if(!loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)){
                //不是管理就扣除，如果是管理员就不扣除
                UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
                userUpdateWrapper.eq("id",loginUser.getId());
                userUpdateWrapper.set("invokeCount",loginUser.getInvokeCount() - UserConstant.AmountDeducted);
                userService.update(userUpdateWrapper);
            }

            //返回结果
            BIResponse biResponse = new BIResponse();
            biResponse.setChartId(chart.getId());
            biResponse.setGenChartCode(chartCode);
            biResponse.setGenChartResult(chartResult);
            return new BIResponseResult(biResponse);
        } catch (Exception e) {
            log.error("syncGenChartHandler exception:",e);
            throw new BusinessException(BISystemEnum.ANALYSE_ERROR.getCode(),BISystemEnum.ANALYSE_ERROR.getMsg());
        }
    }

    /**
     * 上传文件
     * @param file
     * @param chartId
     * @param userId
     * @return
     */
    public Long uploadGenChartFile(MultipartFile file, Long chartId, Long userId){
        List<String> fileNameList = minioUtil.upload(file, FileEnum.SOURCE_FILE.getBucketName());
        SourceFile sourceFile = new SourceFile();
        sourceFile.setUserId(userId);
        sourceFile.setChartId(chartId);
        if(CollectionUtil.isNotEmpty(fileNameList) && fileNameList.size()==2){
            sourceFile.setOriginalFilename(fileNameList.get(0));
            sourceFile.setObjectFileName(fileNameList.get(1));
        }else{
            sourceFile.setOriginalFilename("error: minio保存失败");
        }
        sourceFileMapper.insert(sourceFile);
        return sourceFile.getId();
    }

    private int getIsSuccess(boolean isSuccess){
        return isSuccess ? 0:1;
    }
}
